package repository

import (
	"dataaysn/internal/model"

	"gorm.io/gorm"
)

type ConfigRepository interface {
	Create(config *model.Config) error
	GetByID(id uint) (*model.Config, error)
	GetByCode(code string) (*model.Config, error)
	Update(config *model.Config) error
	Delete(id uint) error
	ListByGroup(groupCode string) ([]model.Config, error)
}

type GormConfigRepository struct {
	db *gorm.DB
}

func NewGormConfigRepository(db *gorm.DB) ConfigRepository {
	return &GormConfigRepository{db: db}
}

func (r *GormConfigRepository) Create(config *model.Config) error {
	return r.db.Create(config).Error
}

func (r *GormConfigRepository) GetByID(id uint) (*model.Config, error) {
	var config model.Config
	err := r.db.First(&config, id).Error
	return &config, err
}

func (r *GormConfigRepository) GetByCode(code string) (*model.Config, error) {
	var config model.Config
	err := r.db.Where("config_code = ?", code).First(&config).Error
	return &config, err
}

func (r *GormConfigRepository) Update(config *model.Config) error {
	return r.db.Save(config).Error
}

func (r *GormConfigRepository) Delete(id uint) error {
	return r.db.Delete(&model.Config{}, id).Error
}

func (r *GormConfigRepository) ListByGroup(groupCode string) ([]model.Config, error) {
	var configs []model.Config
	err := r.db.Where("group_code = ?", groupCode).Find(&configs).Error
	return configs, err
}
